<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Session;
use think\Db;
/**
 * zc_plan 计划表 --张威
 *
 * @icon fa fa-circle-o
 */
class Plan extends Backend
{

    /**
     * Plan模型对象
     * @var \app\admin\model\Plan
     */
    protected $model = null;
    protected $noNeedRight = ['weekPlan','searchList','detail','indexlist','startEndTime','dashMyPlan'];
    protected $dataLimit = 'personal'; //默认基类中为false，表示不启用，可额外使用auth和personal两个值
    protected $dataLimitField = 'admin_id'; //数据关联字段,当前控制器对应的模型表中必须存在该字段
    protected $admin_id = 0;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Plan;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->admin_id = Session::get("admin")['id'];
    }

    public function index()
    {
/*        $planInfo = Db::name("plan")->where('status',1)->select();
        $recordInfo = Db::name("record")->select();
        $record = new \app\admin\model\Record();
        $arr = [];
        foreach($recordInfo as $k => $v){
            foreach($planInfo as $kk => $vv){
                if($v['plan_id'] == $vv['id']){
                    $temp = [];
                    $temp['project_id'] = $vv['project_id'];
                    $temp['id'] = $v['id'];
                    $arr[] = $temp;
                }
            }
        }
        $act=$record->saveAll($arr);*/
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }


    public function indexlist() {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where1 = [];
            $where2 = [];
            $where3 = [];
            $where4 = [];
            if($this->admin_id != 1){
                $where1[] = ['exp',Db::raw("FIND_IN_SET($this->admin_id,admin_id)")];
            }
            $params = $this->request->param();
            if(isset($params['custom'])){
                $custom = $params['custom'];
                if(isset($custom['status'])){
                    $status = $custom['status'];
                    $where2['status'] = $status;
                }
                if(isset($custom['g_id'])){
                    $g_id = $custom['g_id'];
                    $where3['g_id'] = $g_id;
                }
            }
            if(isset($params['searchValue'])){
                $where4['id'] = $params['searchValue'];
            }
            $total = $this->model
                ->where($where)
                ->where($where1)
                ->where($where2)
                ->where($where3)
                ->where($where4)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where($where1)
                ->where($where2)
                ->where($where3)
                ->where($where4)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
    }

    public function import()
    {
        parent::import();
    }

    public function detail($ids){
        $planList = $this->model->get($ids);
        $this->assign('planList',$planList);
        return $this->fetch();
    }


       /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    //所有周计划 暂时废弃
    /*public function weekPlan(){
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        $total = $this->model
            ->where(['status'=>0,'admin_id'=>$this->admin_id])
            ->page($page, $pagesize)
            ->count();
        $list = $this->model
            ->where(['status'=>0,'admin_id'=>$this->admin_id])
            ->page($page, $pagesize)
            ->select();
        $list = collection($list)->toarray();

        return json(['list' => $list, 'total' => $total]);
    }*/

    public function searchList()
    {
        $params = $this->request->param();
        if(isset($params['status'])){
            $where['status'] = ['=',$params['status']];
        }

        //如果是总管理员，能看到所有的计划，如果不是，只能看到自己的计划
        if($this->admin_id!=1){
            $where['admin_id'] = ['=',$this->admin_id];
        }

        $list = $this->model::where($where)->field('title,id')->order('weigh desc')->select();
        if ($list){
            $arr = [];
            foreach($list as $k => $v){
                $arr[$v['id']] = $v['title'];
            }
            $json = json($arr);
        }
        return $json;
    }


    //获取选定类别的计划
    public function getTypePlan(){
        $params = $this->request->param();
        $status = $params['custom']['status'];
        $where['status'] = $status;
        $total = $this->model
            ->where($where)
            ->order('id desc')
            ->count();
        $list = $this->model
            ->where($where)
            ->order('id desc')
            ->select();

        $result = array("total" => $total, "rows" => $list);
        return json($result);
    }


    //获取日 = 0    周 = 1   月 = 2  开始时间 结束时间
    public function startEndTime(){
        $params = $this->request->param();
        $type = $params['type'];
        $info = $this->model->startEndTime($type);
        return json($info);
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                $veriParam = $this->veriParam($params);
                if($veriParam['code'] == 0){
                    $this->error($veriParam['msg']);
                }
                $params = $veriParam['data'];
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign('admin_id',$this->admin_id);
        return $this->view->fetch();
    }


    //过滤参数
    public function veriParam($arr){

        //周计划
        if($arr['status'] == 0){
            if(!$arr['g_id']){
                return ['code'=>0,'msg'=>'请选择月计划','data'=>[]];
            }
            $arr['p_id'] = 0;
            if(!strpos($arr['title'], '（周计划）')&&strpos($arr['title'], '（周计划）')!==0){
                $arr['title'] = '（周计划）'.$arr['title'];
            }
        }
        //日计划
        if($arr['status'] == 1){
            if(!$arr['g_id']){
                return ['code'=>0,'msg'=>'请选择月计划','data'=>[]];
            }
            if(!$arr['p_id']){
                return ['code'=>0,'msg'=>'请选择周计划','data'=>[]];
            }
            if(!strpos($arr['title'], '（日计划）')&&strpos($arr['title'], '（日计划）')!==0){
                $arr['title'] = '（日计划）'.$arr['title'];
            }
        }
        //月计划清理月计划和周计划的值
        if($arr['status'] == 2){
            $arr['g_id'] = 0;
            $arr['p_id'] = 0;
            if(!strpos($arr['title'], '（月计划）')&&strpos($arr['title'], '（月计划）')!==0){
                $arr['title'] = '（月计划）'.$arr['title'];
            }
        }
        return ['code'=>1,'msg'=>'通过验证','data'=>$arr];
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                $veriParam = $this->veriParam($params);
                if($veriParam['code'] == 0){
                    $this->error($veriParam['msg']);
                }
                $params = $veriParam['data'];
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->assign('admin_id',$this->admin_id);
        return $this->view->fetch();
    }

    //首页获取我的计划用
    public function dashMyPlan() {
        $info = $this->model->getInfo(null,null,null,null,$this->admin_id);
        return json(["code"=>1,"msg"=>"获取成功","data"=>$info]);
    }

}
